<template>
  <div id="app" class="skLifeTable">
    <a-card :bordered="true">
      <sk-life-table-header @dataFrom="getDataFrom" v-bind="$attrs" ref="skLifeTableHeader" ></sk-life-table-header>
      <div class="left-circle-icon-box">
        <a-icon type="left-circle"  @click="closeTable" style="font-size: 22px;"/>
      </div>
      <a-row >
        <a-col>
          <a-table :loading="loading" :columns="columns" :pagination="false" :data-source="dataSource" :rowKey="rowKey" bordered :scroll="{x:tebleXScroll,y:800}">
          </a-table>
        </a-col>
      </a-row>
      <a-row style="margin-top: 25px;">
        <a-col>
          <sk-life-student-table v-show="classId !='0'" v-bind="$attrs" :detailName="detailName" ref="skLifeStudentTable" :dataForm="dataForm"></sk-life-student-table>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>
<script>
import { drinkAndToilet } from '@/api/health.js'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil';
import skLifeTableHeader from "@/components/skComponent/TableHeader.vue";
import skLifeStudentTable from "./skLifeStudentTable.vue";
export default {
  name: 'skLifeTable',
  data() {
    return {
      loading:false,
      dataForm:{},
      dataSource: [],
      columns: [],
      classId:"",
      rowKey:"",
      num:3
    }
  },
  props:["detailName"],
  components: {
    skLifeTableHeader,
    skLifeStudentTable
  },

  filters: {},

  computed: {
    tebleXScroll:{
      get(){
        return this.$store.state.skCommon.columnsWidth
      },
      set(val){
        this.$store.dispatch("setcolumnsWidth",val)
      }
    }
  },
  activated() {
  },
  
  mounted() {},
  
  methods: {
    // 关闭表格页面
    closeTable(){
      let data = {
        show:true
      }
      this.$emit("lifeData",data);
    },
    // 获取参数
    getDataFrom(dataForm){
      this.classId = dataForm.classId;
      this.$nextTick(()=>{
        if (dataForm.classId !="0") {
          this.$refs.skLifeStudentTable.getStudentData(dataForm);
        }
      })
      this.getDetail(dataForm);
    },  
    addNUm(){
      this.num ++ ;
      this.$forceUpdate()
    },
    // 详情
    getDetail(dataForm) {
      this.dataForm = dataForm;
      let params = {
        dateType: this.dataForm.dateType=="historySem"?"sem":this.dataForm.dateType,
        queryDate: this.$skCommon.getDate(0),
        classId: this.dataForm.classId == '0' ? null : this.dataForm.classId,
        semesterId:this.dataForm.semesterId == "历史学期" ?this.dataForm.semesterId2:this.dataForm.semesterId
      }
      let url = '';
      if (this.detailName == '喝水') {
        url = '/health/drink/infoList'
      }
      if (this.detailName == '如厕') {
        url = '/health/toilet/infoList'
      }
      if (this.detailName == '睡眠') {
        url = '/health/sleep/selectClassInfo'
      }
      this.columns = [];
      this.loading = true;
      drinkAndToilet(url, params)
        .then(res => {
          if (res.success) {
            let dataColumns = [],dateArr = [],newDate = [];
            if (this.detailName == "睡眠") {
              res.result.forEach(item=>{
                let json = {}
                json = {
                  calssName:item.name,
                  average:item.average.toFixed(2),
                  sleepCount :item.sleepCount.toFixed(2),
                  type:item.type,
                  id:item.id
                };
                item.detail.forEach((j,i) => {
                  dateArr.push(j.date)
                  json["average"+j.date.substring(5,11)] = j.average.toFixed(2);
                  json["sleepCount"+j.date.substring(5,11)] = j.sleepCount.toFixed(2);
                })
                dataColumns.push(json)
              })
              newDate = [...new Set(dateArr)];
              
            }
            if(this.detailName == "喝水" || this.detailName == "如厕"){
              res.result.forEach(item=>{
                let json = {}
                  json = {
                    calssName:item.className,
                    average:item.avg.toFixed(2),
                    type:item.classType,
                    id:item.id,
                    dateType:item.dateType
                  };
                item.detail.forEach((j,i) => {
                  // dateArr.push({
                  //   startDate:j.startDate,
                  //   endDate:j.endDate
                  // })
                  dateArr.push(j.startDate)
                  let tabDate = j.startDate.substring(5,11);
                  if (json['dateType'] == 'sem') {
                    tabDate = j.startDate.substring(5,8);
                  }
                  json["average"+tabDate] = j.avg.toFixed(2);
                  json["count"+tabDate] = j.count.toFixed(2);
                })
                dataColumns.push(json)
              })
              newDate = [...new Set(dateArr)];
              // const map = new Map();
              // newDate = dateArr.filter((item) => !map.has(item["startDate"]) && map.set(item["startDate"], 1));
            }
            this.dataSource = dataColumns;
            this.setColumns(newDate);
            this.loading = false;
          } else {
            this.$message.warning(res.message);
            this.loading = false;
          }
          console.log(this.dataSource);
        })
        .catch(error => {
          console.error(error)
        })
    },
    // 表头
    setColumns(dateArr){
      let columnsTitle = '',columnsTitle2 = ""
      switch (this.dataForm.dateType) {
        case 'month':
          columnsTitle = '周'
          columnsTitle2 = '月'
          break
        case 'sem':
          columnsTitle = '月'
          break
        default:
          columnsTitle2 = '周'
          break
      }
      if (this.detailName == "喝水" || this.detailName == "如厕") {
        this.rowKey = "classId";
        this.columns.push(
          {
            title: '年级',
            align: 'center',
            dataIndex: 'type',
            fixed: 'left',
            width: 100,
            customRender: function(text) {
              return filterDictTextByCache('class_type', text)
            }
          },
          {
            title: '班级',
            align: 'center',
            fixed: 'left',
            width: 140,
            dataIndex: 'calssName'
          },
          {
            title: `${columnsTitle2}${this.detailName}平均次数（次）`,
            align: 'center',
            dataIndex: "average",
          },
        )
        dateArr.sort().forEach((item,i) => {
          let date = "";
          let detailName = this.detailName
          if (this.dataForm.dateType == "week" || this.dataForm.dateType == "month") {
            date = item.substring(5,11)
          }else{
            date = item.substring(5,8)
            detailName = '平均' + detailName
          }
          let json = {}
          let tableHeaderJson = {
            dateType:this.dataForm.dateType,
            startDate:item
          }
          json = {
            title:this.$skCommon.tableHeaderDate(tableHeaderJson),
            align: 'center',
            children: [
              {
                title: `平均${this.detailName}次数（次）`,
                align: 'center',
                dataIndex: `average${date}`,
                customRender: function(text) {
                  return text || '--'
                }
              },
              {
                title: `${this.detailName}次数（次）`,
                align: 'center',
                dataIndex: `count${date}`,
                customRender: function(text) {
                  return text || '--'
                }
              },
            ]
          }
          this.columns.push(json)
        });
      }
      if (this.detailName == "睡眠") {
        this.rowKey = "id";
        console.log(this.rowKey);
        let dataTypeName = ""
        switch (this.dataForm.dateType) {
          case "week":
            dataTypeName = "周"
            break;
          case "month":
            dataTypeName = "月"
            break;
          default:
            dataTypeName = "学期"
            break;
        }
        this.columns = [
          {
            title: '年级',
            align: 'center',
            fixed: 'left',
            dataIndex: 'type',
            width: 100,
            customRender: function(text) {
              return filterDictTextByCache('class_type', text)
            }
          },
          {
            title: '班级',
            align: 'center',
            fixed: 'left',
            width: 140,
            dataIndex: 'calssName'
          },
          {
            title: dataTypeName+'平均睡眠时长(分钟)',
            align: 'center',
            dataIndex: 'average'
          }
        ]
        let _this = this;
        dateArr.sort().forEach(item => {
          let date = "";
          let detailName = _this.detailName
          if (this.dataForm.dateType == "week" || this.dataForm.dateType == "month") {
            date = item.substring(5,11)
          }else{
            date = item.substring(5,8)
            detailName = '平均' + detailName
          }
          let json = {}
            let tableHeaderJson = {
              dateType:this.dataForm.dateType,
              startDate:item
            }
            json = {
              title:this.$skCommon.tableHeaderDate(tableHeaderJson),
              align: 'center',
              children: [
                {
                  title: `${detailName}时长(分钟)`,
                  align: 'center',
                  dataIndex: `average${date}`,
                  customRender: function(text) {
                    return text || '--'
                  }
                },
                // {
                //   title: `总${_this.detailName}时长(分钟)`,
                //   align: 'center',
                //   dataIndex: `sleepCount${date}`,
                //   customRender: function(text) {
                //     return text || '--'
                //   }
                // }
              ]
            }
          this.columns.push(json)
        });
      }
      this.tebleXScroll = this.columns.length;
    },
  }
}
</script>
<style scoped lang="less">
/* @import url(); 引入css类 */
.left-circle-icon-box{
  display: flex;
  justify-content: end;
  margin:10px 0;
  cursor: pointer;
}
</style>
